package org.simp.session;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.mina.core.session.IoSession;
import org.simp.core.message.SimpMessage;
import org.simp.core.message.SimpMessageWraper;

/**
 * @author zhuhaitao at 2014-5-23
 *
 * 
 */
public class SimpSessionWraper  implements SimpSession{

	private IoSession ioSession;
	
	private long sessionId;
	/**
	 * 客户端是用户Id，服务器端是服务器名字，与协议地址中字段对应,同一个用户可能会有多个session，例如，pc，mobile端同时登陆
	 */
	private String sessionName;
	
	private String sessionType;
	
	private long lastSendTime;
	
	private long packetCount;
	
	private Map<String,Object> attributes = new HashMap<String,Object>();

	public SimpSessionWraper(IoSession ioSession){
		this.sessionId = createSessionId();
		this.ioSession = ioSession;
	}
	public SimpSessionWraper(long sessionId,IoSession ioSession){
		this.sessionId = sessionId;
		this.ioSession = ioSession;
	}
	@Override
	public void write(SimpMessage message) {
		ioSession.write(message);
		packetCount ++;
		lastSendTime = System.currentTimeMillis();
	}

	@Override
	public void setSessionName(String sessionName) {
		this.sessionName = sessionName;
		
	}

	@Override
	public void close() {
		if(ioSession != null)
			ioSession.close(true);
		
	}

	public long getSessionId() {
		return sessionId;
	}

	public String getSessionName() {
		return sessionName;
	}

	public long getPacketCount() {
		return packetCount;
	}
	
	
	@Override
	public IoSession getIoSession() {
		// TODO Auto-generated method stub
		return ioSession;
	}
	/**
	 * 根据当前时间和随机数生成一个sessionId
	 * @return
	 * @author zhuhaitao at 2014-5-23
	 */
	private static long createSessionId(){
		Random random = new Random();
		int num = random.nextInt(100);
		long id = System.currentTimeMillis();
		
		id = (id<<16) | (num &0xff);
		return id;
	}
	@Override
	public void addAttribute(String key, Object value) {
		attributes.put(key, value);
		
	}
	@Override
	public Object getAttribute(String key) {
		return attributes.get(key);
	}
	@Override
	public void refresh() {
		if(ioSession != null){
			
		}
		
	}
	@Override
	public void setSessionType(String nodeType) {
		this.sessionType = nodeType;
		
	}
	@Override
	public String getSessionType() {
		return sessionType;
	}
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		sb.append(sessionId).append( "  ");
		sb.append(sessionName).append( "  ");
		sb.append(sessionType).append("  ");
		sb.append(ioSession.toString());
		return sb.toString();
	}
}
